<template>
    <div class="box_wrap" v-loading="loading">
        <div :class="['right_box', showRight ? 'hideBox' : 'showBox']">
            <h3>路口现状图</h3>
            <div class="flex_between">
                <div class="flex_start">
                    <a-input-search v-model:value="roadname" type="text" allowClear autofocus placeholder="搜索" style="height: 34px;"
                        @change="searchKeyword">
                        <template #enterButton>
                            <SearchOutlined @click="searchVal(roadname)" />
                        </template>
                    </a-input-search>

                </div>
                <div class="flex_between">
                    <a-button class="btn_set" @click="addIntersection()">添加</a-button>
                    <a-button class="btn_set" type="primary" v-if="!mapShowMarker" @click="showAllMarker(true)">地图显示</a-button>
                    <a-button class="btn_set" v-else @click="showAllMarker(false)">地图取消</a-button>
                </div>
            </div>
            <el-table :data="list" stripe style="width: 100%" @cell-click="clickRoadTr" >
                <el-table-column prop="title" align="center" label="路口名称" width="200" />
                

                <el-table-column prop="action" label="操作" align="center">
                    <template #default="scope">
                        <el-button
                            link
                            type="primary"
                            size="small"
                            @click="updateDataFunc(0, scope.row,1)"
                        >
                            修改
                        </el-button>

                        <el-popconfirm title="确定删除吗?" @confirm.stop="deleteDataFunc(scope.row.id)">
                            <template #reference>
                            <el-button link type="danger" size="small">删除</el-button>
                            </template>
                        </el-popconfirm>
                        <el-button
                            link
                            type="primary"
                            size="small"
                            @click.stop="updateDataFunc(0, scope.row,2)"
                        >
                            详情
                        </el-button>
                     
                        <el-button
                            link
                            type="primary"
                            size="small"
                            @click.stop="updateDataFunc(0, scope.row,3)"
                        >
                            现状图
                        </el-button>
                       
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                class="mt-10"
                @current-change="changePage"
                :current-page="pageParams.pageNum"
                :page-size="pageParams.pageSize"
                background
                style="float: right;"
                layout="prev, pager, next"
                :total="total"
                hide-on-single-page
            />
        </div>
        <div :class="['icon_show_right', !showRight ? 'right' : 'left']">
            <DoubleLeftOutlined class="icon_show" v-if="!showRight" @click="showBox(showRight)" />
            <DoubleRightOutlined class="icon_hide" v-if="showRight" @click="showBox(showRight)" />
        </div>

        <div class="add_info" v-if="showCtlModal">
            <h3>{{modalType == 1 ? '添加' : modalType == 2 ? '更新' : '查看'}}路口</h3>
            <h4>请先在地图右键选中路口，确定坐标</h4>
            <div class="flex_between item_info">
                <div class="left_text">坐标</div>
                <div class="right_info point">
                    <span>{{ lngNum }}</span>
                    <span>{{ latNum }}</span>
                </div>
            </div>
            <div class="flex_between item_info">
                <div class="left_text">路口名称</div>
                <div class="right_info ">
                    <a-input 
                        v-model:value="intersectionName" 
                        placeholder="输入路口名称(20字内)" 
                        :maxlength="20"
                        :disabled="modalType==3 ? true : false"
                        style="background-color: #999;" 
                        @change="iptValChange(intersectionName)" 
                    />
                </div>
            </div>
            <div class="flex_between item_info">
                <div class="left_text">现状图</div>
                <div class="right_info">
                    <el-upload 
                        ref="editUpload" 
                        class="upload_com"
                        :action="`${baseApiUrl}api/upload/ossPdfFile`" 
                        :headers="headers" 
                        :limit="1"
                        v-model:file-list="fileList"
                        :disabled="modalType==3 ? true : false"
                        accept="pdf"
                        :auto-upload="true" 
                        :before-upload="beforeUpload" 
                        :on-success="uploadSuc"
                        :on-change="uploadDataFunc"
                    >
                        <template #trigger>
                            <el-button type="default" :icon="'Upload'">上传文件</el-button>
                        </template>
                    </el-upload>
                </div>
            </div>
            <div class="flex_between item_info">
                <div class="left_text">备注</div>
                <div class="right_info">
                    <a-textarea 
                        :disabled="modalType==3 ? true : false"
                        :maxlength="100"
                        showCount
                        style="margin-top: 10px;"
                        v-model:value="textAreaVal"
                        @change="textAreaChange(textAreaVal)"
                    ></a-textarea>
                </div>
            </div>

            <div class="flex_around" v-if="modalType != 3">
                <a-button type="primary" @click="saveInfo(1)" v-if="modalType == 1">保存</a-button>
                <a-button type="primary" @click="saveInfo(2)" v-if="modalType == 2">更新</a-button>
                <a-button @click="cancelAdd">取消</a-button>
            </div>
            <div class="flex_around" v-if="modalType == 3">
               
                <a-button @click="cancelAdd">关闭</a-button>
            </div>
        </div>
        <!-- <iframe :src="fileURLOther"></iframe>  -->

    </div>
</template>
<script>
import { defineComponent, ref, computed, shallowRef, watch, reactive, nextTick, onMounted,toRefs} from 'vue';
import { DoubleRightOutlined, DoubleLeftOutlined, SearchOutlined } from '@ant-design/icons-vue';
import useLocalPagination from '@/hooks/useLocalPagination';
import PageSelect from '@/components/PageSelect/index.vue';
import { ACCESS_TOKEN_KEY } from '@/enums/cacheEnum';
import { Storage } from '@/utils/Storage';
import { debounce } from 'lodash-es';
import { ElMessage, ElLoading } from 'element-plus';
import { useMapStore } from '@/store/modules/map';
import axios from "axios";
import { Modal } from 'ant-design-vue';
import { 
    addRoadJunction,
    findAllRoadJunctionList,
    findAllRoadJunctionDetail,
    roadJunctionUpdate,
    delelteRoadJunction,
    getOssTempUrl,

} from '@/api/basic';
export default defineComponent({
    name: 'rightInfo',
    props: {
        intersectionPoint: {
            type: Object,
            default: {},
        },
    },

    components: { PageSelect, DoubleLeftOutlined, DoubleRightOutlined, SearchOutlined, },
    setup(props, { emit }) {
        const upload = ref();
        const loading = ref(false);
        const baseApiUrl = process.env.VUE_APP_BASE_API;
        const token = Storage.get(ACCESS_TOKEN_KEY);
        const mapStore = useMapStore();
        const state = reactive({
            map: computed(() => mapStore.ownMap),
            icon: require("@/assets/images/basic/image.png"),
            upload,
            loading,
            baseApiUrl,
            headers: {
                Authorization: token,
            },
            searchData: [],
            roadname: '',
            lngNum: '',
            latNum: '',
            intersectionName: '',
            textAreaVal:'',
            fileList:[],
            fileKey:'',
            fileName:'',
            tempUrl:'',
            modalType:1,
            updateId:'',
            list:[],
            mapShowMarker:false,
            total:1,
            rightclickPoint:{},
            pageParams:{
                pageSize:10,
                pageNum:1,
                title:'',
            }
        });

        // watch(() => props.intersectionPoint, (val) => {
        //     console.log("intersectionPoint", val);
        //     state.latNum = val.lat
        //     state.lngNum = val.lng
        // });
        const showRight = ref(false);
        const showCtlModal = ref(false);
        const radioList = shallowRef([]); // 
        const radioListSearh = shallowRef([]); // 

        nextTick(() => {
            state.map.addEventListener("rightclick", (e) => {
                // console.log("rightclickPoint", e);
                // console.log("showCtlModal", showCtlModal.value);
                if (e.overlay) {//判断右键单击的是否是marker
                    // setMarkerMenu(e.overlay,true)
                } else {
                    if(!showCtlModal.value){

                    }else if(showCtlModal.value && [1,2].includes(state.modalType)){
                        // state.rightclickPoint = { lng: e.point.lng, lat: e.point.lat };
                        state.latNum = e.point.lat;
                        state.lngNum = e.point.lng;
                        state.map.clearOverlays();
                        var point = new BMap.Point(e.point.lng, e.point.lat);
                        const myIcon = new window.BMap.Icon(state.icon, new window.BMap.Size(35, 35));
                        var marker = new BMap.Marker(point, { icon: myIcon });
                        // console.log("marker",state.markerList);
                        // state.markerList.push(marker)
                        state.map.addOverlay(marker);
                        //没有下面这个会导致右击两次才会有菜单弹出
                        setMarkerMenu(marker,true)
                    }                
                }
                

            })
        });
        const setMarkerMenu = (mkIcon,noData,itemRow) => {
            
            state.menu = new window.BMap.ContextMenu();
            let iconMenuItem = [];
            if(noData){
                iconMenuItem = [
                    {
                        text: '删除', // 定义菜单项的显示文本
                        callback: function (p) {
                            // 定义菜单项点击触发的回调函数
                            if (state.map.getZoom() < 16) {
                            // state.map.panTo(p);
                            // state.map.setZoom(16);
                            }
                            state.map.removeOverlay(mkIcon);
                            state.map.removeContextMenu(state.menu)
                        },
                    },
                ]
            }else{
                iconMenuItem = [
                    {
                        text: '修改', // 定义菜单项的显示文本
                        callback: function (p) {
                            // 定义菜单项点击触发的回调函数
                            if (state.map.getZoom() < 16) {
                                state.map.panTo(p);
                                // state.map.setZoom(16);
                            }
                            // state.map.removeContextMenu(state.menu)
                            updateDataFunc(1,itemRow,1)
                            // console.log("itemRow",itemRow);
                        },
                    },
                    {
                        text: '删除', // 定义菜单项的显示文本
                        callback: function (p) {
                            // 定义菜单项点击触发的回调函数
                            if (state.map.getZoom() < 16) {
                            // state.map.panTo(p);
                            // state.map.setZoom(16);
                            }
                            // state.map.removeOverlay(mkIcon);
                            // deleteDataFunc(itemRow.id)
                            Modal.confirm({
                                title: '提示',
                                // icon: createVNode(ExclamationCircleOutlined),
                                content: '确定删除吗?',
                                onOk() {
                                    deleteDataFunc(itemRow.id)
                                },
                                // eslint-disable-next-line @typescript-eslint/no-empty-function
                                onCancel() {
                                    state.map.clearOverlays();
                                    state.mapShowMarker = false
                                },
                            });
                            state.map.removeContextMenu(state.menu)
                        },
                    },
                    {
                        text: '查看现状图', // 定义菜单项的显示文本
                        callback: function (p) {
                            // 定义菜单项点击触发的回调函数
                            if (state.map.getZoom() < 16) {
                                // state.map.panTo(p);
                            // state.map.setZoom(16);
                            }
                            // state.map.removeContextMenu(state.menu)
                            updateDataFunc(3,itemRow,3)
                            // state.startPoint = p;
                            // addMaker('start', p);
                        },
                    },
                ]
            }


            for (let i = 0; i < iconMenuItem.length; i++) {
                // console.log("iii",i);
                state.menu.addItem(
                new window.BMap.MenuItem(
                    // 定义菜单项实例
                    iconMenuItem[i].text, // 传入菜单项的显示文本
                    iconMenuItem[i].callback, // 传入菜单项的回调函数
                    {
                    width: 100, // 指定菜单项的宽度
                    id: 'menu' + i, // 指定菜单项dom的id
                    },
                ),
                );
            }
            
            mkIcon?.addContextMenu(state.menu);
            // console.log(mkIcon);
        }
        const showBox = (st) => {
            queryAllList()
            showRight.value = !st
        };
        const searchKeyword = debounce((e) => {
            state.roadname = e.target.value
            // console.log(state.roadname)
            state.pageParams.title = e.target.value
            queryAllList()
            // emit('search',state.roadname)
        }, 500);
        const searchVal = (val) => {
            // console.log("searchVal", val);
            state.pageParams.title = val
            queryAllList()
        }

        //路口输入获取
        const iptValChange = debounce((val) => {
            state.intersectionName = val
            // console.log("val", state.intersectionName);
        }, 500)
        //备注
        const textAreaChange = debounce((text)=>{
            state.textAreaVal = text
            console.log("textAreaVal", state.textAreaVal);
        },500)

        const uploadSuc = (suc) => {
            state.loading = false;
            // state.upload.clearFiles();
            const {code ,data:{fileKey,fileName},message,success} = suc
            state.fileKey = fileKey;
            state.fileName = fileName;
            
            // console.log("suc",suc);
        };

        const beforeUpload = (e) => {
            state.loading = true;
            const filetype = e.name?.split('.')[1];
            // console.log("filetype", filetype);
            if (filetype != 'pdf') {
                ElMessage({
                    message: '请上传PDF文件',
                    type: 'warning',
                });
                return false;
            }
        };
        const uploadDataFunc = (e, uploadFile) => { };

        const deleteDataFunc = (id) => {
            delelteRoadJunction(id).then((res) => {
                ElMessage({
                    message: '操作成功',
                    type: 'success',
                });
                state.map.clearOverlays();
                queryAllList();
            });
        };
        const clickRoadTr = (row) => {
            // console.log("row",row);
            state.map.clearOverlays();
            let point = {
                lng:row.coordinate.split(",")[0],
                lat:row.coordinate.split(",")[1],
                id:row.id,
                // url:row.url,
                fileName:row.fileName,
                fileKey:row.fileKey,
                title:row.title,
                remark:row.remark,
                coordinate:row.coordinate,
            }
            
            markerFunc(point)
            setTimeout(()=>{
                const points = new window.BMap.Point(row.coordinate.split(",")[0], row.coordinate.split(",")[1])
                state.map.panTo(points);
            },300)
        }
        //添加路口弹窗
        const addIntersection = () => {
           
            state.latNum = ""
            state.lngNum = ""
            state.intersectionName = ""
            state.textAreaVal = ""
            showCtlModal.value = true
            state.modalType = 1
            state.fileList = []
            
        };

        const cancelAdd = () => {
            showCtlModal.value = false
            state.map.clearOverlays();
            state.mapShowMarker = false
        };
        //查询路口列表
        const queryAllList = () => {

            findAllRoadJunctionList(state.pageParams).then((res) => {
                // console.log("res11", res);
                const {rows,total} = res;
                state.list = rows
                state.total = total
                // data.value = res.data
            });
        
        }
        const changePage = (val) => {
            state.pageParams.pageNum = val;
            queryAllList();
        };
        //保存
        const saveInfo = (ty) => {
            if (state.intersectionName == '') {
                ElMessage({
                    message: '请输入路口名称',
                    type: 'warning',
                });
                return false;
            }
            if (state.lngNum == '') {
                ElMessage({
                    message: '右键选取路口坐标',
                    type: 'warning',
                });
                return false;
            }
            if (state.intersectionName == '') {
                ElMessage({
                    message: '请输入路口名称',
                    type: 'warning',
                });
                return false;
            }
            let params = {
                coordinate:`${state.lngNum},${state.latNum}`,
                title:state.intersectionName,
                // url:'www.123.pdf',
                fileName:state.fileName,
                fileKey:state.fileKey,
                remark:state.textAreaVal,
                
            }
            if(ty === 1){
                addRoadJunction(params).then(res=>{
                // console.log("res",res);
                    state.map.clearOverlays();
                    queryAllList()
                    ElMessage({
                        message: '操作成功',
                        type: 'success',
                    });
                    showCtlModal.value = false
                })
            }else{
                roadJunctionUpdate({...params,id:state.updateId}).then(res=>{                
                    queryAllList()
                    state.map.clearOverlays();
                    ElMessage({
                        message: '操作成功',
                        type: 'success',
                    });
                    showCtlModal.value = false
                })
            }
            // console.log("params",params);
        }
        //获取oss临时文件url
        const getOssTempUrlFunc = (fileKey,fileName,type) =>{
            getOssTempUrl({fileKey}).then(resPdf=>{
                // console.log("resPdf",resPdf);
                const {tempUrl} = resPdf;
                state.tempUrl = tempUrl
                state.fileList = [{
                    uid:fileKey,
                    name:fileName,
                    url:tempUrl,
                }]
                if(type){
                   
                    openPdf()
                    

                }
            })
        }
        //预览PDF
        const openPdf = () => {
            axios({
                method: "get",
                url: state.tempUrl,//文件的url
                params: {
                    fileId: state.fileKey,//文件的id
                },
                responseType: "blob",// 设置返回类型
            }).then((res) => {
                let blob = new Blob([res.data], {
                    type: "application/pdf;chartset=UTF-8",
                });
                state.fileURLOther = URL.createObjectURL(blob);

                window.open(state.fileURLOther, '_blank');

             
            });
        }
        

        
        const updateDataFunc = (funcType,row,type) => {
            // console.log("index",index);
            // console.log("row",row);
            // console.log("type",type);
            const {coordinate,id,remark,title,fileKey,fileName,} = row
            let point = coordinate.split(",")
            state.mapShowMarker = false
            if(type === 1){
                state.modalType = 2
                state.updateId = id;
                state.latNum = point[1]
                state.lngNum = point[0]
                state.intersectionName = title
                state.textAreaVal = remark
                showCtlModal.value = true
                getOssTempUrlFunc(fileKey,fileName)
                
                
                // const points = new window.BMap.Point(point[0], point[1])
                // state.map.panTo(points);
            }else if(type === 2){
                state.modalType = 3
                state.latNum = point[1]
                state.lngNum = point[0]
                state.intersectionName = title
                state.textAreaVal = remark
                showCtlModal.value = true
                getOssTempUrlFunc(fileKey,fileName)
            }else{
                getOssTempUrlFunc(fileKey,fileName,3)
               
            }
        }
        //展示所有路口图标
        const showAllMarker = (ty) => {
            state.mapShowMarker = ty
            if(ty){
                let markerArr = state.list;
            
                let getPointList = markerArr.map(item=>{
                    let obj = {
                        lng:item.coordinate.split(",")[0],
                        lat:item.coordinate.split(",")[1],
                        id:item.id,
                        // url:item.url,
                        fileName:item.fileName,
                        fileKey:item.fileKey,
                        title:item.title,
                        remark:item.remark,
                        coordinate:item.coordinate,
                    } 
                    return obj
                })
                state.map.clearOverlays();
                
                getPointList.map(itemP=>{
                    markerFunc(itemP)
                })
            }else{
                state.map.clearOverlays();
            }
            
            // console.log("getPointList",getPointList);
        }
        const markerFunc = (item) => {
            
            var point = new BMap.Point(item.lng, item.lat);
            const myIcon = new window.BMap.Icon(state.icon, new window.BMap.Size(35, 35));
            var marker = new BMap.Marker(point, { icon: myIcon });
            
            state.map.addOverlay(marker);
            setMarkerMenu(marker,false,item)
        }

        onMounted(() => {
            
        })




        return {
            ...toRefs(state),
            // data,
            showRight,
            showCtlModal,
            // pagination,
            radioList,
            radioListSearh,
            showBox,
            searchKeyword,
            searchVal,
            textAreaChange,
            addIntersection,
            iptValChange,
            beforeUpload,
            uploadSuc,
            uploadDataFunc,
            cancelAdd,
            saveInfo,
            queryAllList,
            changePage,
            clickRoadTr,
            updateDataFunc,
            deleteDataFunc,
            showAllMarker,
            getOssTempUrlFunc,
        }
    }
})
</script>

<style lang="less" scoped>
.box_wrap {
    position: relative;
    height: 90vh;
    width: 100%;

    .add_info {
        position: absolute;
        height: 70vh;
        width: 300px;
        background: rgba(0, 0, 0, 0.8);
        z-index: 5;
        right: 500px;
        top: 30px;
        padding: 10px;
        color: #fff;
        // transform: scale(1);
        transition: width 0.3s;

        h3,
        h4 {
            text-align: center;
            margin-bottom: 10px;
            font-size: 18px;
            color: #fff;

        }

        h4 {
            font-size: 16px;
        }

        .item_info {
            min-height: 48px;
            line-height: 48px;
            height: auto;
            margin-bottom: 20px;
            background-color: #999;

            .left_text {
                width: 70px;
                text-align: center;
            }

            .right_info {
                padding-right: 10px;
                .upload_com{
                    text-align: center;
                }
            }

            .point {
                display: flex;
                flex-direction: column;

                span {
                    height: 24px;
                    line-height: 24px;
                }
            }
        }
    }
}

.icon_show_right {
    color: #fff;
    position: absolute;
    right: 440px;
    top: 215px;
    width: 50px;
    height: 50px;
    z-index: 5;
    text-align: center;
    line-height: 50px;
    transform: translate(-50%, 50%);

    .icon_hide,
    .icon_show {
        color: #fff;
        font-size: 20px;
    }
}

.right {
    right: -10px;
}

.right_box {
    position: absolute;
    right: 30px;
    top: 30px;
    width: 450px;
    height: 70vh;
    background-color: rgba(0, 0, 0, 0.8);
    z-index: 5;
    color: #fff;
    transform: scale(0);
    transition: transform 0.3s;
    padding: 10px;

    h3 {
        text-align: center;
        margin-bottom: 10px;
        font-size: 18px;
        color: #fff;
    }

    .slc_box {
        width: 220px;
        border: 1px solid #fff;
        border-radius: 4px 0 0 4px;
        border-right: 0;
    }

    .btn_search {
        height: 34px;
        line-height: 34px;
        border: 0;
        padding: 0 10px;
        border-radius: 0 4px 4px 0;
    }

    .btn_set {
        padding: 0 10px;

        &:first-child {
            margin-right: 10px;
        }
    }
}

.showBox {
    // width: 0;
    transform: scale(0);
    transition: transform 0.3s;
}
.hideBox{
    transform: scale(1);
    transition: transform 0.3s;
}
</style>